package server;

import container.Mapper;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class SocketProcessor extends Thread {

    private int port;

    private ServerSocket serverSocket;
    private ThreadPoolExecutor threadPoolExecutor;

    public SocketProcessor(int port) {
        this.port = port;
        try {
            serverSocket = new ServerSocket(port);
        }catch (Exception e){
            e.printStackTrace();
        }
        initThreadPool();
    }

    private void initThreadPool(){
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        this.threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }


    @Override
    public void run() {

        try {
            while (true){
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket);
                threadPoolExecutor.execute(requestProcessor);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
